package com.godme.structure;

public class LinkedList {

    private final LinkedNode head = new LinkedNode(-1);


    public void add(int value){
        LinkedNode cursor = head;
        while (cursor.next != null){
            cursor = cursor.next;
        }
        cursor.next = new LinkedNode(value);
    }

    public void deleteByIndex(int index){
        LinkedNode cursor = head;
        while (index > 0 && cursor != null){
            cursor = cursor.next;
            index--;
        }
       connectNextNext(cursor);
    }

    private void connectNextNext(LinkedNode target){
        if(target == null || target.next == null || target.next.next == null){
            return;
        }
        target.next = target.next.next;
    }

    public void deleteByValue(int value){
        LinkedNode cursor = head;
        while (cursor.next!=null && cursor.next.value != value){
            cursor = cursor.next;
        }
        connectNextNext(cursor);
    }

    public void show(){
        StringBuilder sb = new StringBuilder("[");
        LinkedNode cursor = head.next;
        while (cursor != null){
            sb.append(cursor.value);
            if(cursor.next != null){
                sb.append("->");
            }
            cursor = cursor.next;
        }
        System.err.println(sb.append("]"));
    }

    static class LinkedNode{
        int value;
        LinkedNode next;
        public LinkedNode(int value){
            this.value = value;
        }
    }


    public static void main(String[] args) {
        LinkedList linkedList = new LinkedList();
        for (int i = 0; i < 10; i++) {
            linkedList.add(i);
        }
        linkedList.show();

        linkedList.deleteByIndex(3);
        linkedList.show();
        linkedList.deleteByValue(5);
        linkedList.show();
    }



}
